package me.android.library.utils.android;

import android.os.Handler;
import android.os.Looper;
import android.os.Message;

import androidx.annotation.NonNull;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import lombok.experimental.UtilityClass;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@UtilityClass
public class HandlerUtil {
    // 主线程 Handler
    private final Handler MAIN_HANDLER = new Handler(Looper.getMainLooper());

    // 单线程池（用于后台任务）
    private final ExecutorService BACKGROUND_EXECUTOR = Executors.newSingleThreadExecutor();

    // 多线程池（用于并发后台任务）
    private final ExecutorService THREAD_POOL_EXECUTOR = Executors.newFixedThreadPool(3);


    /**
     * 发送空消息
     */
    public void sendEmptyMessage(int what) {
        MAIN_HANDLER.sendEmptyMessage(what);
    }

    /**
     * 延迟发送空消息
     */
    public void sendEmptyMessageDelayed(int what, long delayMillis) {
        MAIN_HANDLER.sendEmptyMessageDelayed(what, delayMillis);
    }

    /**
     * 发送消息
     */
    public void sendMessage(Message msg) {
        MAIN_HANDLER.sendMessage(msg);
    }

    /**
     * 延迟发送消息
     */
    public void sendMessageDelayed(Message msg, long delayMillis) {
        MAIN_HANDLER.sendMessageDelayed(msg, delayMillis);
    }

    /**
     * 移除指定what的所有消息
     */
    public void removeMessages(int what) {
        MAIN_HANDLER.removeMessages(what);
    }

    /**
     * 创建带回调的Handler（使用弱引用避免内存泄漏）
     */
    public Handler createHandler(@NonNull Handler.Callback callback) {
        return new SafeHandler(Looper.getMainLooper(), callback);
    }

    /**
     * 创建带回调的Handler（使用弱引用避免内存泄漏）
     */
    public Handler createHandler(@NonNull Looper looper, @NonNull Handler.Callback callback) {
        return new SafeHandler(looper, callback);
    }


    /**
     * 在主线程执行任务
     */
    public void runOnUiThread(@NonNull Runnable task) {
        if (Looper.myLooper() == Looper.getMainLooper()) {
            // 当前已是主线程，直接执行
            task.run();
        } else {
            // 提交到主线程执行
            MAIN_HANDLER.post(task);
        }
    }

    /**
     * 在主线程延迟执行任务
     */
    public void runOnUiThreadDelayed(@NonNull Runnable task, long delayMillis) {
        MAIN_HANDLER.postDelayed(task, delayMillis);
    }

    /**
     * 移除主线程待执行的任务
     */
    public void removeUiCallbacks(@NonNull Runnable task) {
        MAIN_HANDLER.removeCallbacks(task);
    }

    /**
     * 在后台线程执行任务（单线程顺序执行）
     */
    public void runInBackground(@NonNull Runnable task) {
        BACKGROUND_EXECUTOR.execute(task);
    }

    /**
     * 在后台线程池执行任务（多线程并发）
     */
    public void runInThreadPool(@NonNull Runnable task) {
        THREAD_POOL_EXECUTOR.execute(task);
    }

    /**
     * 关闭线程池（在应用退出时调用）
     */
    public void shutdown() {
        BACKGROUND_EXECUTOR.shutdown();
        THREAD_POOL_EXECUTOR.shutdown();
    }

    /**
     * 周期性执行任务（在主线程）
     */
    public class PeriodicTask {
        private final Handler handler = new Handler(Looper.getMainLooper());
        private final Runnable task;
        private long intervalMillis;
        private boolean isRunning = false;

        public PeriodicTask(@NonNull Runnable task, long intervalMillis) {
            this.task = task;
            this.intervalMillis = intervalMillis;
        }

        private final Runnable periodicRunnable = new Runnable() {
            @Override
            public void run() {
                if (isRunning) {
                    task.run();
                    handler.postDelayed(this, intervalMillis);
                }
            }
        };

        public synchronized void start() {
            if (!isRunning) {
                isRunning = true;
                handler.post(periodicRunnable);
            }
        }

        public synchronized void stop() {
            if (isRunning) {
                isRunning = false;
                handler.removeCallbacks(periodicRunnable);
            }
        }

        public synchronized void setInterval(long intervalMillis) {
            this.intervalMillis = intervalMillis;
            if (isRunning) {
                stop();
                start();
            }
        }
    }

    /**
     * 安全的Handler实现，使用静态内部类避免内存泄漏
     */
    private static class SafeHandler extends Handler {
        private final Handler.Callback callback;

        public SafeHandler(Looper looper, Handler.Callback callback) {
            super(looper);
            this.callback = callback;
        }

        @Override
        public void handleMessage(@NonNull Message msg) {
            if (callback != null) {
                callback.handleMessage(msg);
            }
        }
    }
}